import React from 'react';
import qs from 'query-string';
import connect from '../store/connect';
// import authentication, { autherAndLogin } from '../service/authentication';
import PageLoading from '../components/page-loading';
import { PROJECT_INFO } from '../utils/keys';

export default (route: routeItem) => {
    class RouteHook extends React.Component<Props, State> {
        constructor(props) {
            super(props);
            this.state = {
                authorized: false,
                waitLogin: false
            }
        }
        emptyOpt = {
            des: '您还未登录',
            btnText:  '登  录',
            btnClick: () => this.onOpenChange(true)
        }
        setDocumentTitle(title: string) {
            document.title = title;
        }

        async componentWillMount() {
            // 获取url中的search信息
            const { location } = this.props.history;
            let params = qs.parse(location.search);

            // 检查并添加关键字
            this.redirectByAddKeyword()

            // 如果配置了Name，将name作为title写入document.title
            if (route.name) {
                this.setDocumentTitle(route.name)
            }

            // 检查用户登录状态
           // await this.checkUserLoginStatus(params)

            // 重新设置微信分享信息

            // 初始化用户信息
            this.props.updataUserLoginInfo();

            this.setState({
                authorized: true
            })
        }

        // 检查是否含有指定关键字，若没有获取关键字拼接url重定向
        redirectByAddKeyword = () => {
            const { location } = this.props.history;
            let params = qs.parse(location.search);

            // 如果url中没有标志信息
            if (!('projectId' in params && 'collegeId' in params && 'x_field_1' in params && 'shopId' in params)) {
                // 获取项目和分校信息
                const projectInfo = sessionStorage.getItem(PROJECT_INFO);
                if (!!projectInfo) {
                    let project = JSON.parse(projectInfo)
                    // 将项目和分校信息加在url中重定向
                    this.props.history.replace(
                        qs.stringifyUrl({
                            url: location.pathname,
                            query: {
                                ...params,
                                ...project
                            }
                        })
                    )
                }
            }
        }

        // checkUserLoginStatus = async (params) => {
        //     // 检查用户登录状态
        //     const loginStatusNum = await authentication(route.authorized);

        //     // search参数有meetingID即glive进入
        //     if (params.meetingID) {
        //         // 保存入口meeting信息
        //         localStorage.setItem("glive_meeting_id", params.meetingID as string)
        //     }
            
        //     // 已登录 && 微信环境 && 需授权 &&  --> 检查授权，若无则唤起授权（确保信息完整）
        //     if (loginStatusNum === 1 && window["browser"].iswx && !!route.authorized) {
        //         try {
        //             await autherAndLogin(route.authorized)
        //         } catch (error) {
        //             console.log(error)
        //         }
        //     }

        //     // 非游客 且 非登录状态
        //     if (!route.visitor && loginStatusNum !== 1) {
        //         this.onOpenChange(true);
        //     }
        // }


        onOpenChange = (open: boolean) => {
            this.props.updataBindPhoneVisit(open);
            this.setState({
                waitLogin: open
            })
        }

        handleLoginSuccess = () => {
            this.props.updataUserLoginInfo()
            this.onOpenChange(false);
            window["observer"].emit("loginSuccess")
        }
 
        handleLoginClose = (open: boolean) => {
            this.onOpenChange(open);
        }

        render() {
            let { authorized, waitLogin } = this.state;
            let { loginStatus, bindPhoneVisit } = this.props;

            return (
                // 验证时loading，验证结束后_严格验证路由未登录显示登录提示
                <>
                    <PageLoading 
                        loading={!authorized} 
                        empty={route.userStrict && (!loginStatus.accessToken || loginStatus.needPhoneBind)} 
                        emptyOpt={this.emptyOpt}
                    >
                        {
                            !waitLogin && <route.component route={route}/>
                        }
                    </PageLoading>
                    
                    {/* {
                        (!loginStatus.accessToken || loginStatus.needPhoneBind) &&
                            <DrawerDialog
                                showClose='left'
                                visible={bindPhoneVisit}
                                onOpenChange={this.handleLoginClose}
                            >
                                <Login
                                    loginStatus={loginStatus}
                                    onSuccess={this.handleLoginSuccess}
                                />
                            </DrawerDialog>
                    } */}
                </>
            )
        }
    }

    return connect(RouteHook)
}